
#include <BFont>
#include <BTreeWidget>
#include "member_BTreeItem.h"
#include "member_BTreeWidget.h"

using namespace BWE;

#define tree_member(tree)		((member_BTreeWidget*)((BTreeWidget*)tree)->_ptr)
#define item_member(item)		((member_BTreeItem*)((BTreeItem*)item)->_ptr)

member_BTreeItem::member_BTreeItem(BTreeItem* treeItem)
{
	boss = treeItem;
	tree = 0;
	parent = 0;
	dirty = true;
	expanded = true;
	selected = false;
	align = Align_Left | Align_VCenter;
	indent = 0;
}
member_BTreeItem::~member_BTreeItem()
{

}

void member_BTreeItem::attach(BTreeWidget* treeWidget)
{
	if (tree == treeWidget)
		return;
	tree = treeWidget;
	if (tree)
	{
		tree->addChild(widget);
		for (int i = 0; i < children.size(); i++)
		{
			BTreeItem* item = children[i];
			item_member(item)->attach(tree);
		}
	}
}
void member_BTreeItem::detach(BTreeWidget* treeWidget)
{
	if (tree != treeWidget)
		return;
	if (tree)
	{
		tree->removeChild(widget);
		for (int i = 0; i < children.size(); i++)
		{
			BTreeItem* item = children[i];
			item_member(item)->detach(tree);
		}
	}
	tree = 0;
}

void member_BTreeItem::dirtyTree()
{
	if (tree)
	{
		tree_member(tree)->dirty = true;
		tree->fresh();
	}
}

void member_BTreeItem::adjust()
{
	if (!tree)
		return;

	int arrow = tree_member(tree)->arrowSize;
	int x = rect.x() + indent;
	int y = rect.y();
	int w = rect.width();
	int h = rect.height();

	BRect arrowSpace(x, y, h, h);
	arrowRect = arrowSpace.align(Align_Center, arrow);

	BRect iconArea(x + arrow, y, 0, h);
	if (image)
	{
		iconArea.set(x + arrow, y, h, h);
		BSize iconSize = image->size();
		iconSize.wrap(h);
		imageRect = iconArea.align(Align_Center, iconSize);
	}

	BRect textSpace(iconArea.right(), y, textSize.width(), h);
	textRect = textSpace.align(Align_Center, textSize);
	if (widget)
	{
		widget->setRect(x, y, w, h);
	}

	contentRect.top() = rect.top();
	contentRect.left() = arrowSpace.left();
	contentRect.right() = textSpace.right();
	contentRect.bottom() = rect.bottom();
}

void member_BTreeItem::paint(BPainter& painter)
{
	if (!widget || widget->visible() == false)
	{
		if (image)
		{
			painter.drawImage(imageRect, image);
		}
		else
		{
			painter.setColor(0, 0, 0);
			painter.fillRect(imageRect);
		}
		painter.setColor(Color_Text);
		painter.drawText(textRect, text);
	}
}
